﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.Storage;
using Windows.Storage.FileProperties;
using Windows.Storage.Streams;
namespace Centny.Centny
{
    public class LocalSerialization
    {
        public LocalSerialization()
        {

        }
        public static async Task<Object> Read(String name, Type t)
        {
            StorageFile file;
            file = await ApplicationData.Current.LocalFolder.CreateFileAsync(name, CreationCollisionOption.OpenIfExists);
            object obj = null;
            using (IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.Read))
            {

                System.IO.Stream stream = writeStream.AsStreamForWrite();
                System.Xml.Serialization.XmlSerializer xmlSerializer
                    = new System.Xml.Serialization.XmlSerializer(t);//实例化Xml系列化对象时，仍然要指定类型。
                obj = xmlSerializer.Deserialize(stream);//执行反系列化 
            }
            return obj;
        }
        public static async Task<String> Write(String name, Object t)
        {
            StorageFile file;
            file = await ApplicationData.Current.LocalFolder.CreateFileAsync(name, CreationCollisionOption.OpenIfExists);
            using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync())
            {
                System.IO.Stream stream = transaction.Stream.AsStreamForWrite();
                stream.SetLength(0);
                stream.Flush();
                System.Xml.Serialization.XmlSerializer xmlSerializer
                    = new System.Xml.Serialization.XmlSerializer(t.GetType());//实例化Xml系列化对象时，要指定类型。
                xmlSerializer.Serialize(stream, t);//对obj执行系列化
                stream.Flush();
                await transaction.CommitAsync();
            }
            return "Success";
        }
    }
}
